package com.company.planner.web.screens.esclusterconfig;

import com.company.planner.entity.ActiveEnum;
import com.company.planner.entity.EsClusterConfig;
import com.company.planner.service.EsService;
import com.google.common.base.Strings;
import com.haulmont.cuba.core.global.DataManager;
import com.haulmont.cuba.gui.Dialogs;
import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.RemoveOperation;
import com.haulmont.cuba.gui.app.core.inputdialog.DialogActions;
import com.haulmont.cuba.gui.app.core.inputdialog.InputDialog;
import com.haulmont.cuba.gui.app.core.inputdialog.InputParameter;
import com.haulmont.cuba.gui.components.Button;
import com.haulmont.cuba.gui.components.DialogAction;
import com.haulmont.cuba.gui.components.TreeTable;
import com.haulmont.cuba.gui.components.ValidationErrors;
import com.haulmont.cuba.gui.model.CollectionLoader;
import com.haulmont.cuba.gui.screen.*;
import org.slf4j.Logger;

import javax.inject.Inject;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;

@UiController("planner_EsClusterConfig.browse")
@UiDescriptor("es-cluster-config-browse.xml")
@LookupComponent("esClusterConfigsTable")
@LoadDataBeforeShow
public class EsClusterConfigBrowse extends StandardLookup<EsClusterConfig> {
    @Inject
    private Logger log;
    @Inject
    private Dialogs dialogs;
    @Inject
    private Notifications notifications;
    @Inject
    private EsService esService;
    @Inject
    private CollectionLoader<EsClusterConfig> esClusterConfigsDl;
    @Inject
    private TreeTable<EsClusterConfig> esClusterConfigsTable;
    @Inject
    private DataManager dataManager;

    @Subscribe("dynamicBtn")
    public void onDynamicBtnClick(Button.ClickEvent event) {
        dialogs.createInputDialog(this)
                .withCaption("动态生成配置")
                .withParameters(
                        InputParameter.stringParameter("ip").withCaption("IP: "),
                        InputParameter.stringParameter("port").withCaption("端口: ")
                )
                .withValidator(validationContext -> {
                    //设置input框
                    String ip = validationContext.getValue("ip");
                    String port = validationContext.getValue("port");
                    if (Strings.isNullOrEmpty(ip)) {
                        return ValidationErrors.of("IP不能为空");
                    }
                    if (Strings.isNullOrEmpty(port) || port.length() > 4) {
                        return ValidationErrors.of("端口格式错误,长度低于四位");
                    }
                    //设置正则格式校验
                    String regex = "((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))";
                    boolean matches = Pattern.matches(regex, ip);
                    if (!matches) {
                        return ValidationErrors.of("IP格式错误");
                    }
                    return ValidationErrors.none();
                })
                .withActions(DialogActions.OK_CANCEL)
                .withCloseListener(inputDialogCloseEvent -> {
                    if (inputDialogCloseEvent.getCloseAction().equals(InputDialog.INPUT_DIALOG_OK_ACTION)) {

                        String ip = inputDialogCloseEvent.getValue("ip");
                        int port = Integer.parseInt(Objects.requireNonNull(inputDialogCloseEvent.getValue("port")));

                        if (!esService.buildClusterState(ip, port)) {
                            notifications.create(Notifications.NotificationType.TRAY)
                                    .withCaption("该节点已存在！")
                                    .show();
                        }

                        //刷新
                        esClusterConfigsDl.load();
                    }
                })
                .show();
    }

    @Install(to = "esClusterConfigsTable.remove", subject = "afterActionPerformedHandler")
    private void esClusterConfigsTableRemoveAfterActionPerformedHandler(RemoveOperation.AfterActionPerformedEvent<EsClusterConfig> afterActionPerformedEvent) {
        //刷新
        esClusterConfigsDl.load();
    }

    @Subscribe("disableBtn")
    public void onDisableBtnClick(Button.ClickEvent event) {
        Set<EsClusterConfig> esClusterConfigs = esClusterConfigsTable.getSelected();
        dialogs.createOptionDialog()
                .withCaption("禁用集群")
                .withMessage("确认禁用该集群？")
                .withType(Dialogs.MessageType.CONFIRMATION)
                .withActions(
                        new DialogAction(DialogAction.Type.OK)
                                .withHandler(e -> {
                                    if (!esClusterConfigs.isEmpty()) {
                                        for (EsClusterConfig esClusterConfig : esClusterConfigs) {
                                            esClusterConfig.setActive(ActiveEnum.NO);
                                            dataManager.commit(esClusterConfig);
                                        }
                                    }
                                }),
                        new DialogAction(DialogAction.Type.CANCEL))
                .show();
    }

    @Subscribe("enableBtn")
    public void onEnableBtnClick(Button.ClickEvent event) {
        Set<EsClusterConfig> esClusterConfigs = esClusterConfigsTable.getSelected();
        dialogs.createOptionDialog()
                .withCaption("启用集群")
                .withMessage("确认启用该集群？")
                .withType(Dialogs.MessageType.CONFIRMATION)
                .withActions(
                        new DialogAction(DialogAction.Type.OK)
                                .withHandler(e -> {
                                    if (!esClusterConfigs.isEmpty()) {
                                        for (EsClusterConfig esClusterConfig : esClusterConfigs) {
                                            esClusterConfig.setActive(ActiveEnum.YES);
                                            dataManager.commit(esClusterConfig);
                                        }
                                    }
                                }),
                        new DialogAction(DialogAction.Type.CANCEL))
                .show();
    }


}